#!/bin/bash

set -o errexit
set -o errtrace
set -o pipefail
set -o nounset

readonly progpath="$(realpath "$0")"
readonly progname="$(basename "$progpath")"
readonly progdir="$(dirname "$progpath")"
if [ -d "pkg/mingw-w64-i686-ruby" ]; then
    readonly _d="pkg/mingw-w64-i686-ruby/mingw32/"
else
    readonly _d="pkg/mingw-w64-x86_64-ruby/mingw64/"
fi

ruby_default() {
  for f in ${_d}/lib/ruby/gems/*/specifications/default/*; do
    if [ -f "$f" ]; then
      echo $(basename ${f%.*}) | sed -r 's/(.*)-/\1=/'
    fi
  done
}

ruby_bundled() {
  for f in ${_d}/lib/ruby/gems/*/cache//*; do
    if [ -f "$f" ]; then
      echo $(basename ${f%.*}) | sed -r 's/(.*)-/\1=/'
    fi
  done
}

usage() {
    echo "   Usage: $progname"
    echo
    echo "   ruby and gawk (mingw-w64) needs to be installed"
    echo
    [[ "${1:-}" =~ ^[0-9]{1,3}$ ]] && exit $1
}

command -v gawk &>/dev/null || usage 1

declare -r tmpfile="$(mktemp)"
ruby_bundled \
| while IFS='' read -r line; do
    echo "$line"
done | sort -f > "$tmpfile"

ruby_default \
| while IFS='' read -r line; do
    echo "$line"
done | sort -f >> "$tmpfile"

mv "PKGBUILD" "PKGBUILD~"

gawk '
/^provides=/ { s = 1 }
s && /)/ {
    s = 0
    print "provides=("
    while ( (getline line < "'"$tmpfile"'") > 0 ) {
        print "    \"${MINGW_PACKAGE_PREFIX}-ruby-" line "\""
    }
    print ")"
    next
}
s { next }
! s { print }
' "PKGBUILD~" > "PKGBUILD"

rm "$tmpfile"

# vim: set ts=4 sw=4 et ai:
